//
//  UIColor+Extension.m
//  XYLib
//
//  Created by blts on 2018/3/30.
//  Copyright © 2018年 XYLib. All rights reserved.
//

#import "UIColor+Extension.h"

@implementation UIColor (Extension)

+ (UIColor *)colorWithHexString:(NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
+(UIColor *)colorWithStr:(NSString *)colorStr
{
    //    NSString *color = @“#FF0000”;
    // 转换成标准16进制数
    //    [colorStr replaceCharactersInRange:[colorStr rangeOfString:@"#"] withString:@"0x"];
    colorStr = [colorStr stringByReplacingOccurrencesOfString:@"#" withString:@"0x"];
    //    [colorStr stringByReplacingOccurrencesOfString:@"#" withString:@"0x"];
    // 十六进制字符串转成整形。
    long colorLong = strtoul([colorStr cStringUsingEncoding:NSUTF8StringEncoding], 0, 16);
    // 通过位与方法获取三色值
    int R = (colorLong & 0xFF0000 )>>16;
    int G = (colorLong & 0x00FF00 )>>8;
    int B =  colorLong & 0x0000FF;
    
    //string转color
    UIColor *color = [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:1.0];
    return color;
}

+(UIColor *)colorWithStr:(NSString *)colorStr WithAlpha:(CGFloat)alpha
{
    //    NSString *color = @“#FF0000”;
    // 转换成标准16进制数
    //    [colorStr replaceCharactersInRange:[colorStr rangeOfString:@"#"] withString:@"0x"];
    colorStr = [colorStr stringByReplacingOccurrencesOfString:@"#" withString:@"0x"];
    //    [colorStr stringByReplacingOccurrencesOfString:@"#" withString:@"0x"];
    // 十六进制字符串转成整形。
    long colorLong = strtoul([colorStr cStringUsingEncoding:NSUTF8StringEncoding], 0, 16);
    // 通过位与方法获取三色值
    int R = (colorLong & 0xFF0000 )>>16;
    int G = (colorLong & 0x00FF00 )>>8;
    int B =  colorLong & 0x0000FF;
    
    //string转color
    UIColor *color = [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:alpha];
    return color;
}
@end
